package cn.edu.gxnu.dsa.queue;

public class CircleSequenceQueue implements IQueue {
	private Object[] queueElement;
	private int front;
	private int rear;

	public CircleSequenceQueue(int maxSize) {
		front = 0;
		rear = 0;
		queueElement = new Object[maxSize];
	}

	@Override
	public void clear() {
		front = 0;
		rear = 0;
	}

	@Override
	public boolean isEmpty() {
		return front == rear;
	}

	@Override
	public int length() {
		return (rear - front + queueElement.length) % queueElement.length;
	}

	@Override
	public Object peek() {
		if (front == rear) {
			return null;
		}
		return queueElement[front];
	}

	@Override
	public void enQueue(Object o) {
		if ((rear + 1) % queueElement.length == front) {
			System.err.println("The queue is full!");
		} else {
			queueElement[rear] = o;
			rear = (rear + 1) % queueElement.length;
		}

	}

	@Override
	public Object deQueue() {
		if (front == rear) {
			return null;
		} else {
			Object o = queueElement[front];
			front = (front + 1) % queueElement.length;
			return o;
		}
	}

	public void display() {
		if (!isEmpty()) {
			for (int i = front; i != rear; i = (i + 1) % queueElement.length) {
				System.out.print(queueElement[i] + " ");
			}
		} else {
			System.out.println("The queue is empty!");
		}
	}

}
